package com.niit.chat.utils;

import com.niit.chat.dto.SessionVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class RedisMessageHandler {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 向指定用户发送消息
     *
     * @param userId 用户ID
     * @param payload 消息内容
     */
    public void sendMessageToUser(Long userId, String payload) {
        try {
            String channel = "user:" + userId + ":messages";
            redisTemplate.convertAndSend(channel, payload);
            log.info("Sent message to user {}: {}", userId, payload);
        } catch (Exception e) {
            log.error("Failed to send message to user {}", userId, e);
        }
    }

    /**
     * 发送会话更新消息给所有连接的客户端
     */
    public void notifySessionUpdated(SessionVO sessionVO) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new JavaTimeModule());
            String json = mapper.writeValueAsString(sessionVO);
            
            // 发送到会话更新频道
            redisTemplate.convertAndSend("session-updates", json);
            log.info("Sent session update: {}", json);
        } catch (Exception e) {
            log.error("Failed to send session update", e);
        }
    }

    /**
     * 通知消息撤回
     *
     * @param senderId 发送者ID
     * @param receiverId 接收者ID
     * @param messageId 消息ID
     */
    public void notifyMessageRecalled(Long senderId, Long receiverId, Long messageId) {
        // 构建一个撤回消息的通知体
        Map<String, Object> payload = new HashMap<>();
        payload.put("type", "message_recalled");
        payload.put("messageId", messageId);

        try {
            String jsonPayload = new ObjectMapper().writeValueAsString(payload);
            // 给发送方和接收方都发送通知
            sendMessageToUser(senderId, jsonPayload);
            sendMessageToUser(receiverId, jsonPayload);
        } catch (Exception e) {
            // 处理序列化异常
            log.error("Failed to notify message recall", e);
        }
    }
}